﻿@model OrderListModel
           
@using System.Web.Script.Serialization
@using Telerik.Web.Mvc.UI

@{
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    var hideProfitReport = false;
    
    //page title
    ViewBag.Title = T("Admin.Orders").Text;
}


    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/Administration/Content/images/ico-sales.png")" alt="" />
            @T("Admin.Orders")
        </div>
        <div class="options">
            <a href="@Url.Action("ExportXmlAll")" class="t-button">@T("Admin.Common.ExportToXml.All")</a>
            <input type="button" id="exportxml-selected" class="t-button" value="@T("Admin.Common.ExportToXml.Selected")" />
            <a href="@Url.Action("ExportExcelAll")" class="t-button">@T("Admin.Common.ExportToExcel.All")</a>
            <input type="button" id="exportexcel-selected" class="t-button" value="@T("Admin.Common.ExportToExcel.Selected")" />
        </div>
    </div>

<!-- ko with: OrderSearchFilterModel -->

<table width="100%">
    <tr>
        <td class="adminTitle">
            @Html.NopLabelFor(model => model.StartDate):
        </td>
        <td class="adminData">
            @*  @Html.EditorFor(model => model.StartDate)*@
            <input type="text" data-bind="value:StartDate"/>
        </td>
    </tr>
    <tr>
        <td class="adminTitle">
            @Html.NopLabelFor(model => model.EndDate):
        </td>
        <td class="adminData">
            @*@Html.EditorFor(model => Model.EndDate)*@
            <input type="text" data-bind="value:EndDate"/>
        </td>
    </tr>
    <tr>
        <td class="adminTitle">
            @Html.NopLabelFor(model => model.CustomerEmail):
        </td>
        <td class="adminData">
            @*@Html.EditorFor(model => Model.CustomerEmail)*@
                
            <input type="text" data-bind="value:CustomerEmail"/>
        </td>
    </tr>
    <tr>
        <td class="adminTitle">
            @Html.NopLabelFor(model => model.OrderStatusId):
        </td>
        <td class="adminData">
             <select data-bind="options: AvailableOrderStatuses, optionsText: 'Text', value: OrderStatusId,optionsValue:'Value'"></select>


      @*      @Html.DropDownList("OrderStatusId", Model.AvailableOrderStatuses)*@
        </td>
    </tr>
    <tr>
        <td class="adminTitle">
            @Html.NopLabelFor(model => model.PaymentStatusId):
        </td>
        <td class="adminData">
            
            <select data-bind="options: AvailablePaymentStatuses, optionsText: 'Text', value: PaymentStatusId,optionsValue:'Value'"></select>

          @*  @Html.DropDownList("PaymentStatusId", Model.AvailablePaymentStatuses)*@
        </td>
    </tr>
    <tr>
        <td class="adminTitle">
            @Html.NopLabelFor(model => model.ShippingStatusId):
        </td>
        <td class="adminData">
          @*  @Html.DropDownList("ShippingStatusId", Model.AvailableShippingStatuses)*@
            
            <select data-bind="options: AvailableShippingStatuses, optionsText: 'Text', value: ShippingStatusId,optionsValue:'Value'"></select>
        </td>
    </tr>
    <tr>
        <td class="adminTitle">
            @Html.NopLabelFor(model => model.OrderGuid):
        </td>
        <td class="adminData">
         @*   @Html.EditorFor(model => Model.OrderGuid)*@
            
              <input type="text" data-bind="value:OrderGuid"/>
        </td>
    </tr>
    @* <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GoDirectlyToNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.GoDirectlyToNumber)
                <input type="submit" name="go-to-order-by-number" class="t-button" value="@T("Admin.Common.Go")" />
            </td>
        </tr>*@
    <tr>
        <td colspan="2">
           @* <input type="button" id="btnSearch" class="t-button" value="@T("Admin.Common.Search")" />*@
                
            <input type="button" class="t-button" data-bind="click:$root.DoSearch"  value="@T("Admin.Common.Search")"/>
        </td>
    </tr>
</table>
<!-- /ko -->


<p></p>

<div class="t-grid t-widget">
    

<table>
    <thead class="t-grid-header">
        <tr><th class="t-header" scope="col">OrderId</th>
            <th class="t-header" scope="col" style="text-align:center">OrderStatus</th>
            <th class="t-header" scope="col"><span class="t-link">PaymentStatus</span></th>
            <th class="t-header" scope="col"><span class="t-link">ShippingStatus</span></th>
            <th class="t-header" scope="col" style="text-align:center;">CustomerEmail</th>
            <th class="t-header" scope="col" style="text-align:center;">CreatedOn</th>
            <th class="t-header" scope="col" style="text-align:center;"></th>

        </tr>
    </thead>

    <tbody>
        
    <!-- ko foreach: OrderListItems -->
    <tr>
        <td>
            <span data-bind="text:Id"></span>
        </td>
        <td>
            <span data-bind="text:OrderStatus"></span>
        </td>
         <td>
            <span data-bind="text:PaymentStatus"></span>
        </td>
        <td>
            <span data-bind="text:ShippingStatus"></span>
        </td>
        <td>
            <span data-bind="text:CustomerEmail"></span>
        </td>
        <td>
            <span data-bind="text:CreatedOn"></span>
        </td>
        <td>
            <a data-bind="attr:{href:Url}" >Edit</a>
        </td>
    </tr>
     <!-- /ko -->
    </tbody>
</table>
    </div>

@{ 
    var jsonData = new HtmlString(new JavaScriptSerializer().Serialize(Model));
}

<script type="text/javascript">
    var initialData = @jsonData;

        function OrderListItemModel(id,orderStatus,paymentStatus,shippingStatus,customerEmail,createdOn,orderTotal) {
            this.Id= ko.observable(id);
            this.OrderStatus = ko.observable(orderStatus);
            this.PaymentStatus = ko.observable(paymentStatus);
            this.ShippingStatus = ko.observable(shippingStatus);
            this.CustomerEmail = ko.observable(customerEmail);
            this.CreatedOn = ko.observable(createdOn);
            this.OrderTotal = ko.observable(orderTotal);
            this.Url = ko.observable("/Admin/Order/Edit/" + id);

        }

        function OrderSearchFilterModel(startDate,
            endDate,
            customerEmail, 
            availableOrderStatus, 
            orderStatusId, 
            availablePaymentStatuses,
            paymentStatusId,
            availableShippingStatuses,
            shippingStatusId,
            orderGuid) 
        {
            
            this.StartDate = ko.observable(startDate);
            this.EndDate = ko.observable(endDate);
            this.CustomerEmail = ko.observable(customerEmail);


            this.AvailableOrderStatuses = ko.observableArray(availableOrderStatus);
            this.OrderStatusId = ko.observable(orderStatusId);


            this.AvailablePaymentStatuses = ko.observableArray(availablePaymentStatuses);
            this.PaymentStatusId = ko.observable(paymentStatusId);
            
            this.AvailableShippingStatuses = ko.observableArray(availableShippingStatuses);
            this.ShippingStatusId = ko.observable(shippingStatusId);

            this.OrderGuid = ko.observable(orderGuid);
            
            //this.pageIndex = ko.observable(1);
            //this.pageSize = ko.observable(30);
        }

        function OrderListModel() {
            var self = this;

            self.OrderSearchFilterModel = new OrderSearchFilterModel(initialData.StartDate, 
                initialData.EndDate,  
                initialData.CustomerEmail, 
                initialData.AvailableOrderStatuses, 
                initialData.OrderStatusId,
                initialData.AvailablePaymentStatuses,
                initialData.PaymentStatusId,
                initialData.AvailableShippingStatuses,
                initialData.ShippingStatusId,
                ""
            );
            
            
            self.OrderListItems = ko.observableArray([]);
            
            self.DoSearch = function() {
                $.ajax({
                    url: "/Admin/Order/OrderListJson",
                    type: 'post',
                    data:  ko.toJSON({model:self.OrderSearchFilterModel, pageIndex:0,pageSize:30}),
                    contentType: 'application/json',
                    success: function (result) {
                        self.OrderListItems.removeAll();
                    
                        var items = $.map(result.Result, function (a) {
                            return new OrderListItemModel(a.Id, a.OrderStatus, a.PaymentStatus, a.ShippingStatus, a.CustomerEmail, a.CreatedOn, a.OrderTotal);
                        });
                        self.OrderListItems(items);
                    }
                });
                
                //$.post('/Admin/Order/OrderListJson', ko.toJSON({model:self.OrderSearchFilterModel, pageIndex:1,pageSize:30}), function(result) {

                //    self.OrderListItems.removeAll();
                    
                //    var items = $.map(result.Result, function (a) {
                //        return new OrderListItemModel(a.ProductId, a.ProductPictureUrl, a.ProductName, a.ProductUrl, a.Sort);
                //    });
                //    self.OrderListItems(items);
                //});
            };

        }

        ko.applyBindings(new OrderListModel());       
        
        var selectedIds = [];
        var reportAggregates = "";

        $(document).ready(function () {

            //search button
            $('#btnSearch').click(function () {
                //search
                var grid = $('#orders-grid').data('tGrid');
                grid.currentPage = 1; //new search. Set page size to 1
                grid.ajaxRequest();
                //clear selected checkboxes
                $('.checkboxGroups').attr('checked', false).change();
                selectedIds = [];
                return false;
            });


            //"Export Excel selected" button
            $('#exportexcel-selected').click(function (e) {
                e.preventDefault();
                //redirect to required URL
                setLocation('@(Url.Action("ExportExcelSelected", "Order"))?selectedIds=' + selectedIds.join(","));
                return false;
            });

            //"Export XML selected" button
            $('#exportxml-selected').click(function (e) {
                e.preventDefault();
                //redirect to required URL
                setLocation('@(Url.Action("ExportXmlSelected", "Order"))?selectedIds=' + selectedIds.join(","));
                return false;
            });

            
            $('#mastercheckbox').click(function () {
                $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
            });

            //wire up checkboxes. 
            $('#orders-grid input[type=checkbox][id!=mastercheckbox]').live('change', function (e) {
                var $check = $(this);
                if ($check.is(":checked") == true) {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked == -1) {
                        //add id to selectedIds.  
                        selectedIds.push($check.val());
                    }
                }
                else {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked > -1) {
                        //remove id from selectedIds.  
                        selectedIds = $.grep(selectedIds, function (item, index) {
                            return item != $check.val();
                        });
                    }
                }
                updateMasterCheckbox();
            });
        });

        function onDataBinding(e) {
            var searchModel = {
                    StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
                    EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
                    CustomerEmail: $('#@Html.FieldIdFor(model => model.CustomerEmail)').val(),
                    OrderStatusId: $('#@Html.FieldIdFor(model => model.OrderStatusId)').val(),
                    PaymentStatusId: $('#@Html.FieldIdFor(model => model.PaymentStatusId)').val(),
                    ShippingStatusId: $('#@Html.FieldIdFor(model => model.ShippingStatusId)').val(),
                    OrderGuid: $('#@Html.FieldIdFor(model => model.OrderGuid)').val()
                    };
            e.data = searchModel;
        }
    
        function onDataBound(e) {

            $('#orders-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
                var currentId = $(this).val();
                var checked = jQuery.inArray(currentId, selectedIds);
                //set checked based on if current checkbox's value is in selectedIds.  
                $(this).attr('checked', checked > -1);
            });

            updateMasterCheckbox();

            reportLoaded(e);
        }

        function onComplete(e) {
            var result = e.response;
            if (result) {
                reportAggregates = e.response["aggregates"];
            }
        }

        function reportLoaded(e) {
            if (reportAggregates != "") {
                updateAggregates(reportAggregates);
            }
        }
        function updateAggregates(aggs) {
            for (var key in aggs) {

                @if (!hideProfitReport)
                {
                <text>$('#aggregator-profit-block').text(aggs['aggregatorprofit']);</text>
                }
                $('#aggregator-tax-block').text(aggs['aggregatortax']);
                $('#aggregator-total-block').text(aggs['aggregatortotal']);
            }
        }

        function updateMasterCheckbox() {
            var numChkBoxes = $('#orders-grid input[type=checkbox][id!=mastercheckbox]').length;
            var numChkBoxesChecked = $('#orders-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
            $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
        }
   </script>
    